<template>
  <div class="dashboard-container">
    <el-container>
      <el-header>
        <div style="left: 34%">
          <label style="color: #fff; font-size: 2.0rem">新光光电-电力故障监控预测大屏</label>
        </div>
      </el-header>
      <el-container>
        <el-aside width="16.5rem">
          <div>
            <div class="title">
              <label>数据接入</label>
            </div>
            <div style="text-align: left;padding: 10px 0">
              <span slot="label" style="float: left; color: greenyellow"><i class="el-icon-date"/>离线接入</span>
              <span slot="label" style="float: right"><i class="el-icon-date"/>在线接入</span>
              <el-row>
                <el-col style="float: top; margin-top: 20%">
                  <div style="margin: 5px 0;">
                    <label class="aside-label">环境数据预览</label>
                    <el-table
                      :data="environmentData"
                      :cell-style="{ color: '#fff' }"
                      :header-cell-style="{ color: '#fff' }"
                      style="font-size: 0.4rem;"
                      max-height="250"
                    >
                      <el-table-column
                        label="设备名称"
                      >
                        <template slot-scope="scope">
                          <el-popover trigger="hover" placement="top" width="150">
                            <p>{{ scope.row.equipmentName }}</p>
                            <div slot="reference">
                              <p size="medium" style="white-space: nowrap;overflow: hidden;text-overflow:ellipsis;">
                                {{ scope.row.equipmentName }}</p>
                            </div>
                          </el-popover>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="equipmentTemperature"
                        label="设备温度"
                      />
                      <el-table-column
                        prop="checkTime"
                        label="检测时间"
                      />
                    </el-table>
                  </div>
                </el-col>
                <el-col style="float: bottom; margin-top: 20%">
                  <div style="height: 50%">
                    <!--              <el-upload
                      class="upload-demo"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      multiple
                      :limit="1"
                      :on-exceed="handleExceed"
                      :file-list="fileList"
                    >
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">请上传环境数据文件，且不超过10MB</div>
                    </el-upload>-->
                    <el-upload
                      action=""
                      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                      :on-change="onUploadChangeTemperature"
                      :auto-upload="false"
                      :limit="1"
                      :on-exceed="handleExceed"
                      :show-file-list="true"
                    >
                      <el-button slot="trigger" size="small" type="primary">选取环境数据表</el-button>
                      <el-button style="margin-left: 10px;" size="small" type="success" @click="onUploadTemperature">
                        上传
                      </el-button>
                      <div slot="tip" class="el-upload__tip">请上传环境数据文件，且不超过10MB</div>
                    </el-upload>
                    <!--              <el-upload
                      class="upload-demo"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      multiple
                      :limit="1"
                      :on-exceed="handleExceed"
                      :file-list="fileList"
                    >
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">请上传电流数据文件，且不超过10MB</div>
                    </el-upload>-->
                    <el-upload
                      action=""
                      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                      :on-change="onUploadChangeCurrent"
                      :auto-upload="false"
                      :limit="1"
                      :on-exceed="handleExceed"
                      :show-file-list="true"
                      style="margin-top: 20%"
                    >
                      <el-button slot="trigger" size="small" type="primary">选取电流数据表</el-button>
                      <el-button style="margin-left: 10px;" size="small" type="success" @click="onUploadCurrent">上传
                      </el-button>
                      <div slot="tip" class="el-upload__tip">请上传电流数据文件，且不超过10MB</div>
                    </el-upload>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-aside>
        <el-main>
          <div style="display: block;text-align: left;font-size: 1.5rem; margin-left: 16%">
            <el-row>
              <el-col :span="12"><label style="color: yellowgreen">环境数据量：</label>{{ totalData.envCount }}条<br><label
                style="color: yellowgreen">告警数据量：</label>{{ totalData.alarmCount }}条
              </el-col>
              <el-col :span="12"><label style="color: yellowgreen">电流数据量：</label>{{ totalData.currentCount }}条<br><label
                style="color: yellowgreen">特征数据量：</label>{{ totalData.featureCount }}条
              </el-col>
            </el-row>
            <img src="../../assets/divider.png" style="object-fit: fill;">
          </div>
          <el-row>
            <!-- 中间电流和预测数据 -->
            <el-col :span="12">
              <!--              <el-image :src="predictImageUrl" style="height: 300px; width: 400px;margin-left: 8%;"-->
              <!--                        :style="{visibility:predictImageUrl?'visible':'hidden'}"></el-image>-->
              <div id="mainMiddleLine" style="height: 300px; width: 400px;margin-left: 8%;"/>
            </el-col>
            <!-- TOP排行 -->
            <el-col :span="12">
              <div id="mainRightBar" style="height: 300px; width: 400px;margin-left: 10%"/>
            </el-col>
          </el-row>
          <div id="bottom"
               style="float: none;height: 55px;color: darkgoldenrod;display: block;padding-top:10px;font-weight: bold;background-color: #1f2d3d">
            <label>机号</label>
            <el-select v-model="selectedDeviceNumber" placeholder="请选择" size="small" style="margin-left: 1%">
              <el-option
                v-for="item in deviceNumberOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <label style="margin-left: 10px;">子设备</label>
            <el-select v-model="selectedDeviceName" placeholder="请选择" size="small" style="margin-left: 1%">
              <el-option
                v-for="item in deviceNameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <!--            <label for="date" style="margin-left: 10%;">时间 </label>
                        <input id="date" type="date" name="date" value="2021" style="border-color: darkslategray;border-width: 0px;border-radius: 5%;">-->
            <span class="demonstration" style="margin-left: 1%;">时间</span>
            <el-date-picker
              size="small"
              v-model="queryDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
            <!--<button id="btn" style="margin-left: 10px;" @click="btnClick">确定</button>-->
            <el-button style="margin-left: 10px;" size="small" plain icon="el-icon-search" @click="btnClick">确定
            </el-button>
          </div>
          <div id="mainBottomLine" style="height: 300px;margin-top: 1%"/>
        </el-main>
        <el-aside width="15rem">
          <div style="padding: 5px 0">
            <div class="title">
              <label>模型训练与预测</label>
            </div>
            <div style="display: block; padding: 5px">
              <span>模型选择：</span>
              <el-select v-model="selectedModel" clearable placeholder="请选择" style="width: 60%" size="small">
                <el-option
                  v-for="item in modelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div style="float: left;margin-left: 3%">
              <h5 style="color: greenyellow;font-size: small">模型训练</h5>
              <el-row>
                <el-col>
                  <el-progress :stroke-width="12" type="circle" :percentage="trainPercentage"
                               :color="trainProgressColorChange"/>
                </el-col>
                <el-col>
                  <el-button type="primary" size="small" @click="onTrainModel">模型训练</el-button>
                </el-col>
              </el-row>
              <h5/>
              <h5/>
              <h5 style="color: greenyellow;font-size: small">模型预测</h5>
              <el-row>
                <el-col>
                  <el-progress :stroke-width="12" type="circle" :percentage="predictPercentage" :color="predictColors"/>
                </el-col>
                <el-col>
                  <el-button type="primary" size="small" @click="onPredictModel">模型预测</el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col style="margin-top: 10%;margin-left: 0%;font-size: smaller">
                  <label style="color: yellowgreen">LSTM平均绝对误差: </label>
                  <label v-if="this.lstmDeviation.length !== 0">{{ this.lstmDeviation[0] }}</label>
                </el-col>
                <el-col style="margin-top: 10%;margin-left: 0%;font-size: smaller;">
                  <label style="color: yellowgreen">LSTM均方根误差: </label>
                  <label v-if="this.lstmDeviation.length !== 0">{{ this.lstmDeviation[1] }}</label>
                </el-col>
                <el-col style="margin-top: 10%;margin-left: 0%;font-size: smaller">
                  <label style="color: yellowgreen">GRU平均绝对误差: </label>
                  <label v-if="this.gruDeviation.length !== 0">{{ this.gruDeviation[0] }}</label>
                </el-col>
                <el-col style="margin-top: 10%;margin-left: 0%;font-size: smaller">
                  <label style="color: yellowgreen">GRU均方根误差: </label>
                  <label v-if="this.gruDeviation.length !== 0">{{ this.gruDeviation[1] }}</label>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-aside>
        <el-dialog title="模型训练参数" :visible.sync="dialogFormVisible">
          <el-form :model="trainParamForm">
            <el-form-item label="layer" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.layerArgv" placeholder="神经元层数，默认值32"></el-input>
            </el-form-item>
            <el-form-item label="dropout" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.dropoutArgv" placeholder="剪枝层丢弃率，默认值0.2"></el-input>
            </el-form-item>
            <el-form-item label="dense" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.denseArgv" placeholder="Dense层，默认值6"></el-input>
            </el-form-item>
            <el-form-item label="loss" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.lossArgv" placeholder="损失函数，默认值mae"></el-input>
            </el-form-item>
            <el-form-item label="monitor" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.monitorArgv" placeholder="监控函数，默认值val_loss"></el-input>
            </el-form-item>
            <el-form-item label="patience" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.patienceArgv" placeholder="patience值，默认值3"></el-input>
            </el-form-item>
            <el-form-item label="factor" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.factorArgv" placeholder="影响因子，默认值0.5"></el-input>
            </el-form-item>
            <el-form-item label="min_lr" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.min_lrArgv" placeholder="min_lr值，默认值0.00001"></el-input>
            </el-form-item>
            <el-form-item label="batch_size" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.batch_sizeArgv" placeholder="批处理数量，默认值64"></el-input>
            </el-form-item>
            <el-form-item label="epochs" :label-width="trainParamFormLabelWidth">
              <el-input v-model="trainParamForm.epochsArgv" placeholder="迭代次数，默认值100"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="startTrainModel">确 定</el-button>
          </div>
        </el-dialog>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import {
  pre, one, pre2, uploadTemperatureExcel, uploadCurrentExcel, trainModel, predictModel, getAvailableModel,
  getDeviceNumbers, getDeviceNames, getCount, getCurrentCompare, getPearsonParam, getTemperatureTop,
  getTodayTemperature, previewCurrentTable, previewEnvironmentTable, totalData, getData
} from '@/api/power'
import $ from '@/api/jquery'

export default {
  data() {
    return {
      predictImageUrl: '',
      totalData: {},
      modelOptions: [{
        value: 'GRU',
        label: 'GRU'
      }, {
        value: 'LSTM',
        label: 'LSTM'
      }],
      selectedModel: '',
      dialogFormVisible: false,
      trainParamForm: {
        generatingModel: '',
        layerArgv: '32',
        dropoutArgv: '0.2',
        denseArgv: '6',
        lossArgv: 'mae',
        monitorArgv: 'val_loss',
        patienceArgv: '3',
        factorArgv: '0.5',
        min_lrArgv: '0.00001',
        batch_sizeArgv: '64',
        epochsArgv: '100'
      },
      trainParamFormLabelWidth: '120px',
      deviceNameOptions: [
        {
          value: 'xxx套线管',
          label: 'xxx套线管'
        }, {
          value: 'xxx升高座',
          label: 'xxx升高座'
        }
      ],
      selectedDeviceName: '',
      deviceNumberOptions: [
        {
          value: '1号机',
          label: '1号机'
        }, {
          value: '2号机',
          label: '2号机'
        }
      ],
      selectedDeviceNumber: '',
      environmentData: [],
      mainMiddleLineOption: {
        title: {
          text: '趋势预测',
          textStyle: {
            color: 'white'
          }
        },
        legend: {
          orient: 'vertical',
          x: 'right', // 可设定图例在左、右、居中
          y: 'top', // 可设定图例在上、下、居中
          textStyle: {
            color: 'white'
          }
        },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          /* {
            name: '实际',
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true
          }, */
          {
            name: 'LSTM',
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true
          },
          {
            name: 'GRU',
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true
          },
          {
            name: '真实值',
            data: [1, 2, 3, 4, 5, 6, 7],
            type: 'line',
            smooth: true
          }
        ]
      },
      mainMiddleLineChartDom: '',
      mainMiddleLineChart: '',
      mainRightBarOption: {
        title: {
          text: '设备数据量TOP5排行',
          textStyle: {
            color: 'white'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'vertical',
          x: 'right', // 可设定图例在左、右、居中
          y: 'top', // 可设定图例在上、下、居中
          textStyle: {
            color: 'white'
          }
        },
        grid: {
          // left: '3%',
          // right: '4%',
          // bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 1],
          axisLabel: {
            color: 'rgba(255,255,255,1)',
            fontSize: '8'
          }
        },
        yAxis: {
          type: 'category',
          data: ['Brazil', 'Indonesia', 'USA', 'India', 'China', 'World'],
          axisLabel: {
            color: 'rgba(255,255,255,1)',
            fontSize: '8',
            interval: 0,
            formatter: function (params) {
              var newParamsName = '' // 最终拼接成的字符串
              var paramsNameNumber = params.length // 实际标签的个数
              var provideNumber = 8 // 每行能显示的字的个数
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber) // 换行的话，需要显示几行，向上取整
              /**
               * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
               */
              // 条件等同于rowNumber>1
              if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                for (var p = 0; p < rowNumber; p++) {
                  var tempStr = '' // 表示每一次截取的字符串
                  var start = p * provideNumber // 开始截取的位置
                  var end = start + provideNumber // 结束截取的位置
                  // 此处特殊处理最后一行的索引值
                  if (p === rowNumber - 1) {
                    // 最后一次不换行
                    tempStr = params.substring(start, paramsNameNumber)
                  } else {
                    // 每一次拼接字符串并换行
                    tempStr = params.substring(start, end) + '\n'
                  }
                  newParamsName += tempStr // 最终拼成的字符串
                }
              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params
              }
              // 将最终的字符串返回
              return newParamsName
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(131,101,101,0.2)',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '录入系统记录数',
            type: 'bar',
            data: [19325, 23438, 31000, 121594, 134141, 681807]
          }
        ]
      },
      mainRightBarChartDom: '',
      mainRightBarChart: '',
      mainBottomChart: '',
      fileList: [],
      temperatureFiles: [], // 要上传的文件
      currentFiles: [], // 要上传的文件
      // 定时器 http://www.bubuko.com/infodetail-3494109.html
      predictLoading: false,
      trainPercentage: 0, // 加载进度条初始值
      predictPercentage: 0, // 加载进度条初始值
      trainInterval: 0, // 加载的定时器
      predictInterval: 0, // 加载的定时器
      trainTimeStop: 0, // 加载成功停止的定时器
      predictTimeStop: 0, // 加载成功停止的定时器
      customColor: '#409eff',
      trainColors: [
        {color: '#f56c6c', trainPercentage: 20},
        {color: '#e6a23c', trainPercentage: 40},
        {color: '#5cb87a', trainPercentage: 60},
        {color: '#1989fa', trainPercentage: 80},
        {color: '#6f7ad3', trainPercentage: 100}
      ],
      predictColors: [
        {color: '#f56c6c', predictPercentage: 20},
        {color: '#e6a23c', predictPercentage: 40},
        {color: '#5cb87a', predictPercentage: 60},
        {color: '#1989fa', predictPercentage: 80},
        {color: '#6f7ad3', predictPercentage: 100}
      ],
      queryDate: '',
      lstmDeviation: [],
      gruDeviation: []
    }
  },
  created() {
  },
  mounted() {
    this.load()
    this.previewEnvironmentTable()
    this.getCurrentCompare()
    this.getTemperatureTop()
    this.loadTotalData()
    this.loadBottomLine()
  },
  methods: {
    trainProgressColorChange() {
      if (this.trainPercentage < 30) {
        return '#f56c6c'
      } else if (this.trainPercentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    },
    // 训练模型进度条
    onTrainProgress() {
      const that = this
      const endPro = 98
      that.trainInterval = setInterval(function () {
        // 如果没有生成结果文件，++
        if (that.trainPercentage < endPro) {
          that.trainPercentage++
        }
      }, 100)
    },
    // 预测模型进度条
    onPredictProgress() {
      const that = this
      const endPro = 98
      that.predictInterval = setInterval(function () {
        // 如果没有生成结果文件，++
        if (that.predictPercentage < endPro) {
          that.predictPercentage++
        }
      }, 1000)
    },
    loadTotalData() {
      totalData().then(res => {
        if (res.code === 20000) {
          this.totalData = res.data.data
        } else {
          alert('加载预览数据失败')
        }
      })
    },
    load() {
      getAvailableModel().then(res => {
        if (res.code === 20000) {
          this.modelOptions = res.data.data
        } else {
          alert('加载模型列表失败')
        }
      })
      getDeviceNames().then(res => {
        if (res.code === 20000) {
          this.deviceNameOptions = res.data.data
        } else {
          alert('加载设备名称失败')
        }
      })
      getDeviceNumbers().then(res => {
        if (res.code === 20000) {
          this.deviceNumberOptions = res.data.data
        } else {
          alert('加载设备机号失败')
        }
      })
      one().then((res) => {
        if (res.code === 20000) {
          const obj = eval(res.data.data)
          if (res.data === null) {
            alert('不存在当前数据文件夹')
          }
          this.loadBottomLine(obj)
        } else {
          alert('无此文件！')
        }
      })
    },
    btnClick() {
      const deviceNum = this.selectedDeviceNumber
      const deviceName = this.selectedDeviceName
      const date = this.queryDate
      if (date !== '' && deviceName !== '' && deviceNum !== '') {
        this.getData(deviceNum, deviceName, date)
      } else {
        console.info(deviceNum + ':' + deviceName + ':' + date)
        this.$message.error('请选择设备机号、设备名称和日期')
      }
      // alert("option.series=>" + option.series);
      // console.log(date)
    }, // btnClick
    onUploadChangeTemperature(file) {
      this.temperatureFiles = file.raw
    },
    onUploadChangeCurrent(file) {
      if (this.currentFiles.length !== 0) {
        this.$message.warning('只能上传一个文件')
      }
      this.currentFiles = file.raw
    },
    handleExceed() {
      this.$message.warning('只能上传一个文件')
    },
    onUploadTemperature() {
      // const files = document.getElementById('uploadFile').files
      console.log(this.temperatureFiles)
      if (this.temperatureFiles.length === 0) {
        this.$message.error('请选择待上传的文件')
        return
      }
      const formData = new FormData()
      formData.append('temperaturefile', this.temperatureFiles)
      formData.append('date', '')
      uploadTemperatureExcel(formData).then(response => {
        if (response.code === 20000) {
          alert('上传设备温度文件成功')
          this.loadTotalData()
        } else {
          alert('上传设备温度文件失败')
        }
      })
    }, // onUploadTemperature
    onUploadCurrent() {
      // const files = document.getElementById('uploadFile').files
      if (this.currentFiles.length === 0) {
        this.$message.error('请选择待上传的文件')
        return
      }
      const formData = new FormData()
      formData.append('currentfile', this.currentFiles)
      formData.append('date', '')
      uploadCurrentExcel(formData).then(response => {
        if (response.code === 20000) {
          alert('上传电流文件成功')
          this.loadTotalData()
        } else {
          alert('上传电流文件失败')
        }
      })
    }, // onUploadCurrent
    getData(deviceNum, deviceName, date) {
      const data = {'date': date, 'deviceName': deviceName, 'deviceNum': deviceNum}
      one(data).then((res) => {
        if (res.code === 20000) {
          const obj = eval(res.data.data)
          if (res.data === null) {
            alert('不存在当前数据文件夹')
          }
          this.loadBottomLine(obj)
        } else {
          alert('无此文件！')
        }
      })
    }, // getData
    onTrainModel() {
      if (this.selectedModel === '') {
        this.$message.error('请选择模型')
        return
      }
      // 显示弹框
      this.dialogFormVisible = true
      // 填写并赋值
    }, // onTrainModel
    startTrainModel() {
      // 隐藏弹框
      this.dialogFormVisible = false
      this.trainParamForm.generatingModel = this.selectedModel
      var data = this.trainParamForm
      // 调用进度条
      this.onTrainProgress()
      trainModel(data).then(response => {
        if (response.code === 20000) {
          const that = this
          that.trainPercentage = 100
          // this.$message.success('模型训练完成')
          this.$alert('模型训练完成', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              // 清除之前的状态
              clearInterval(that.trainInterval)
              that.trainTimeStop = setTimeout(() => {
                that.trainPercentage = 0
                clearTimeout(that.trainTimeStop)
              })
            }
          })
        } else {
          this.$alert('模型训练失败', '提示')
        }
        console.log(response)
      })
    }, // startTrainModel
    onPredictModel() {
      if (this.selectedModel === '') {
        this.$message.error('请选择模型')
        return
      }
      // 调用进度条
      this.onPredictProgress()
      predictModel(this.selectedModel).then(response => {
        if (response.code === 20000) {
          const that = this
          that.predictPercentage = 100
          this.$alert('模型预测完成', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              // 清除之前的状态
              clearInterval(that.predictInterval)
              that.predictTimeStop = setTimeout(() => {
                that.predictPercentage = 0
                clearInterval(that.predictTimeStop)
              })

              console.log(111)
              //
              // that.predictImageUrl = process.env.VUE_APP_BASE_API + 'GRU.png?time=' + Date.now().toString()

              // // 渲染表格
              const data = response.data.data
              this.mainMiddleLineChartDom = document.getElementById('mainMiddleLine')
              this.mainMiddleLineChart = this.$echarts.init(this.mainMiddleLineChartDom)
              // console.log(data)
              if (this.selectedModel === 'LSTM') {
                this.mainMiddleLineOption.series[0].data = data[0]
                this.mainMiddleLineOption.series[1].data = []
                this.mainMiddleLineOption.series[2].data = data[3]
                this.lstmDeviation = data[2]
              } else {
                this.mainMiddleLineOption.series[0].data = []
                this.mainMiddleLineOption.series[1].data = data[0]
                this.mainMiddleLineOption.series[2].data = data[3]
                this.gruDeviation = data[2]
              }
              // this.mainMiddleLineOption.series[2].data = []
              this.mainMiddleLineOption.xAxis.data = data[1]
              this.mainMiddleLineOption && this.mainMiddleLineChart.setOption(this.mainMiddleLineOption)
            }
          })
        } else {
          this.$alert('模型预测失败', '提示')
        }
        console.log(response)
      })
    }, // onPredictModel
    previewEnvironmentTable() {
      previewEnvironmentTable().then(res => {
        if (res.code === 20000) {
          this.environmentData = res.data.data
        } else {
          alert('加载预览数据失败')
        }
      })
    }, // previewEnvironmentTable
    previewCurrentTable() {
      previewCurrentTable().then(res => {
        if (res.code === 20000) {
          this.tableData = res.data.data
        } else {
          alert('加载预览数据失败')
        }
      })
    }, // previewCurrentTable
    getCurrentCompare() {
      this.mainMiddleLineChartDom = document.getElementById('mainMiddleLine')
      this.mainMiddleLineChart = this.$echarts.init(this.mainMiddleLineChartDom)
      predictModel('GRU').then(res => {
        if (res.code === 20000) {
          const data = res.data.data
          this.mainMiddleLineOption.series[0].data = []
          this.mainMiddleLineOption.series[1].data = data[0]
          this.mainMiddleLineOption.series[2].data = data[3]
          this.mainMiddleLineOption.xAxis.data = data[1]
          this.mainMiddleLineOption && this.mainMiddleLineChart.setOption(this.mainMiddleLineOption)
        } else {
          alert('加载预览数据失败')
        }
      })
      getCurrentCompare().then(res => {
        if (res.code === 20000) {
          /*const data = res.data.data
          console.log(data)
          this.mainMiddleLineOption.series[0].data = data[0]
          this.mainMiddleLineOption.series[1].data = data[1]
          // this.mainMiddleLineOption.series[2].data = data[2]
          this.mainMiddleLineOption.xAxis.data = data[2]
          this.mainMiddleLineOption && this.mainMiddleLineChart.setOption(this.mainMiddleLineOption)
          this.lstmDeviation = data[3]
          this.gruDeviation = data[4]*/
        } else {
          alert('加载预览数据失败')
        }
      })
    }, // getCurrentCompare
    getTemperatureTop() {
      this.mainRightBarChartDom = document.getElementById('mainRightBar')
      this.mainRightBarChart = this.$echarts.init(this.mainRightBarChartDom)
      getTemperatureTop().then(res => {
        if (res.code === 20000) {
          const data = res.data.data
          this.mainRightBarOption.series[0].data = data['xAxis']
          this.mainRightBarOption.yAxis.data = data['yAxis']
          this.mainRightBarOption && this.mainRightBarChart.setOption(this.mainRightBarOption)
        } else {
          alert('加载预览数据失败')
        }
      })
    },
    loadBottomLine(data) {
      this.init(data)
    },
    init(data) {
      // https://www.cnblogs.com/cplemom/p/11123565.html
      // 每行最多显示4个图表，并自动计算高度
      var num = this.getRound(3, 50)
      var rowNumber = Math.ceil(Math.sqrt(num))
      if (rowNumber > 4) {
        rowNumber = 4
      }
      // 根据列数计算行数
      var colummNumber = Math.ceil(num / rowNumber)

      // 指定行列数据
      rowNumber = 4
      colummNumber = 1
      // 上下图表间隔
      var topNum = 30
      // 固定单个图表高度
      var heightNum = 250
      // 计算所需要的高度
      document.getElementById('mainBottomLine').style.height = colummNumber * (heightNum + topNum) + 'px'

      // 基于准备好的dom，初始化echarts实例
      if (this.mainBottomChart === '') {
        this.mainBottomChart = this.$echarts.init(document.getElementById('mainBottomLine'))
      }
      var grids = []
      var xAxis = []
      var yAxis = []
      var series = []
      var titles = []

      var xdata = ['第1次', '第2次', '第3次', '第4次', '第5次', '第6次']
      var titleArr = ['设备温度', '环境温度', '环境湿度', '风速']
      if (data === null || typeof (data) === 'undefined') {
        return
      }
      xdata = data[0]

      // 通过配置xAxi和yAxis的gridIndex  series的xAxisIndex和yAxisIndex 来配套格子
      for (var i = 0; i < num; i++) {
        xAxis.push({
          type: 'category',
          data: xdata,
          gridIndex: i
        })
        yAxis.push({
          type: 'value',
          gridIndex: i,
          inverse: true,
          splitLine: {
            show: false
          }
        })
        series.push({
          name: '名次',
          type: 'line',
          // data: this.getRandom(6),
          data: data[i + 1],
          xAxisIndex: i,
          yAxisIndex: i,

          label: {
            show: true
          }
        })

        grids.push({
          // show: true
        })

        titles.push({
          textAlign: 'center',
          text: titleArr[i],
          textStyle: {
            fontSize: 16,
            color: 'white',
            fontWeight: 'normal'
          }
        })
      }

      // 通过计算配置各个grid  title的位置
      grids.forEach((grid, idx) => {
        grid.left = ((idx % rowNumber) / rowNumber) * 100 + 3 + '%'
        grid.top = (Math.floor(idx / rowNumber) * (heightNum + topNum)) + top

        grid.width = (1 / rowNumber) * 100 - 6 + '%'
        grid.height = heightNum - 6

        titles[idx].left = parseFloat(grid.left) + parseFloat(grid.width) / 2 + '%'
        titles[idx].top = parseFloat(grid.top)
      })

      // 指定图表的配置项和数据
      var option = {
        title: titles,
        xAxis: xAxis,
        yAxis: yAxis,
        series: series,
        grid: grids
      }

      // 使用刚指定的配置项和数据显示图表。
      this.mainBottomChart.setOption(option)
    },
    getRound(min, max) {
      return parseInt(Math.random() * (max - min + 1) + min)
    },
    // 获取min-max范围内的随机整数
    getRandom(num) {
      var list = []
      for (var i = 0; i < num; i++) {
        list.push(this.getRound(1, 100))
      }
      return list
    }
  }
}
</script>

<style scoped>
.el-header, .el-footer {
  /* background-color: #B3C0D1; */
  background-image: url(../../assets/title.png);
  background-size: 100%;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  /* background-color: #D3DCE6; */
  text-align: center;
}

.el-main {
  /* background-color: #E9EEF3; */
  text-align: center;
}

.upload-demo {
  margin: 10px;
}

.dashboard-container {
  /*margin-bottom: 40px;*/
  background-image: url('../../assets/background.png');
  background-size: 100%;
  height: 100%;
  color: #fff;
}

.title {
  font-size: 1.5rem;
  color: #fff;
  background-image: url('../../assets/title1.png');
  background-size: 100%;
}

.aside-label {
  font-size: 20px;
  margin-top: 10px;
}

::v-deep .el-table,
::v-deep .el-table__expanded-cell {
  background-color: transparent !important;
}

/* 表格内背景颜色 */
::v-deep .el-table th,
::v-deep .el-table tr,
::v-deep .el-table td {
  background-color: transparent !important;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 5px;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.3);
}
</style>

